import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';

type ResponseData = any; // 定义响应数据的类型

const instance = axios.create({
  baseURL: '/v1/admin',
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config: any) => {
    // 添加时间戳到URL中
    if (!config.url.includes('?')) {
      config.url += '?';
    } else if (!config.url.endsWith('&') && !config.url.endsWith('?')) {
      config.url += '&';
    }
    config.url += `timestamp=${Date.now()}`;

    // 在这里添加token或其他请求前的逻辑
    // config.headers.Authorization = `Bearer ${getToken()}`;
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

const handleErrorResponse = (error: AxiosError) => {
  if (error.response) {
    const status = error.response.status;
    switch (status) {
      case 404:
        console.error(
          `Resource not found at URL: ${error.response.config.url}`,
        );
        break;
      case 405:
        console.error(
          `Method not allowed for URL: ${error.response.config.url}`,
        );
        break;
      case 500:
        console.error('Internal server error occurred.');
        break;
      default:
        console.error('An unexpected error occurred.');
    }
  }
};

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    return response.data;
  },
  (error: AxiosError) => {
    handleErrorResponse(error);
    return Promise.reject(error);
  },
);


// 封装请求方法
const request = {
  get: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
    instance.get<T>(url, { params, ...config }),
  post: <T>(url: string, data?: object, config?: AxiosRequestConfig) =>
    instance.post<T>(url, data, config),
  put: <T>(url: string, data?: object, config?: AxiosRequestConfig) =>
    instance.put<T>(url, data, config),
  delete: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
    instance.delete<T>(url, { params, ...config }),
};

export default request;
